$(function () {
    $("#jqGrid").jqGrid({
        url: (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + 'sys/user/list',
        datatype: "json",
        colModel: [			
			{ label: '用户ID', name: 'id', index: "user_id", width: 45, key: true },
			{ label: '登录名', name: 'username', width: 75 },
			{ label: '用户名', name: 'fullName', width: 75 },
            { label: '所属部门', name: 'deptName', sortable: false, width: 75 },
			{ label: '邮箱', name: 'email', width: 90 },
			{ label: '手机号', name: 'mobile', width: 100 },
			{ label: '状态', name: 'status', width: 60, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">禁用</span>' : 
					'<span class="label label-success">正常</span>';
			}},
            {
                label: '用户类型', name: 'userType', width: 60, formatter: function (value, options, rpw) {
                    if (value === 3) {
                        return '普通用户';
                    }
                    if (value === 2) {
                        return '实验员';
                    }
                    if (value === 1) {
                        return '管理员';
                    }
                    return '系统用户';
                }
            },
			{ label: '创建时间', name: 'createDate', index: "createDate", width: 85}
        ],
		viewrecords: true,
        height:"100%",
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el:'#myapp',
    data:{
        q:{
            username: null
        },
        showList: true,
        title:null,
        roleList:{},
        user:{
            status:1,
            // userType:0,
            deptId:null,
            deptName:null,
            roleIdList:[]
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.roleList = {};
            vm.user = {deptName:null, deptId:null, status:1, roleIdList:[]};
            // vm.user = {deptName:null, deptId:null, status:1, roleIdList:[],userType:0};

            //获取角色信息
            this.getRoleList();
            vm.getDept();
            vm.getUserTypeList();
        },
        getDept: function(){
            //加载部门树
            $.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/dept/list", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r);
                console.log(r);
                var node = ztree.getNodeByParam("id", vm.user.deptId);
                if(node != null){
                    ztree.selectNode(node);

                    vm.user.deptName = node.name;
                }
            })
        },
        update: function () {
            var userId = getSelectedRow();
            if(userId == null){
                return ;
            }

            vm.showList = false;
            vm.title = "修改";

            vm.getUser(userId);
            //获取角色信息
            this.getRoleList();

            vm.getUserTypeList();
        },
        del: function () {
            var userIds = getSelectedRows();
            if(userIds == null){
                return ;
            }

            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/user/delete",
                    contentType: "application/json",
                    data: JSON.stringify(userIds),
                    success: function(r){
                        if(r.code == 0){
                        	toast('操作成功');
                            vm.reload(); 
                        }else{
                        	warning(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function () {
            var url = vm.user.id == null ? "sys/user/save" : "sys/user/update";
            vm.user.userType = $("#userType").val();
            $.ajax({
                type: "POST",
                url: (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url,
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function(r){
                    if(r.code === 0){
                    	toast('操作成功');
                        vm.reload(); 
                    }else{
                    	warning(r.msg);
                    }
                }
            });
        },
        getUser: function(userId){
            $.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/user/info/"+userId, function(r){
                vm.user = r.user;
                vm.user.password = null;

                vm.getDept();
                vm.getUserTypeList();
            });
        },
        getRoleList: function(){
            $.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/role/select", function(r){
                vm.roleList = r.list;
            });
        },
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.user.deptId = node[0].id;
                    vm.user.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
        },
        getUserTypeList: function () {
        	var url = "sys/dict/listByType/userType";
        	var $userType =$("#userType");
        	$userType.empty();
        	$.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url,function (r) {
        		$.each(r.list,function (item,obj) {
                    var $option = '';
                    if(obj.code == '3'){
                         $option = $("<option value='"+obj.code+"' selected>"+obj.value+"</option>");
                    }else {
                         $option = $("<option value='"+obj.code+"'>"+obj.value+"</option>");
                    }
	        		$userType.append($option);
        		});
        	});       	
        },
        openImportExcel: function (event) {
            openImportExcel();
        },
        importExcel: function (event) {
            let prefix = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/user";
            importExcel(prefix, null, vm);
        },
        exportExcel: function (event) {
            let prefix = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/user";
            exportExcel(prefix);
        },
        exportExcelTemplate: function (event) {
            let prefix = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/user";
            exportExcelTemplate(prefix);
        },
        changeUserType: function (event) {
            var $userType =$("#userType");
        	var checkUserType = $userType.val();
        	if(checkUserType === '0') {
        		$("#userInfoDiv").css("display","none");
        	}else {
        		$("#userInfoDiv").css("display","block");
        	}
        	vm.getInfoList(checkUserType);
        },
        getInfoList: function (userType) {
        	
        	var url = "";
        	var $userInfoId = $("#userInfoId");
        	$userInfoId.empty();
        	//教师
        	if (userType === '1') {
        		url = "tp/teacher/select";
        		$.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url,function (r) {
        		$.each(r.list,function (item,obj) {
	        		var $option = $("<option value='"+obj.id+"'>"+obj.teacherNd+" "+obj.name+"</option>");
	        		$userInfoId.append($option);
        		});
        	}); 
        	}
        	
        	//学生
        	if (userType === '2') {
        		url = "tp/student/select";
        		$.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url,function (r) {
	        		$.each(r.list,function (item,obj) {
		        		var $option = $("<option value='"+obj.id+"'>"+obj.studentNo+" "+obj.name+"</option>");
		        		$userInfoId.append($option);
	        		});
	        	}); 
        	}
        }
    }
});